import {defineStore} from "pinia"
import {login} from "../api/Login/index"

export const useTokenStore = defineStore("login",{
  state:()=>({
    user:{
      token:"",
      username:"",
      userId:"",
      phoneNumber:"",
      addressArray: [],
      balance: 0,
      nickname: "",
      avatarUrl: "",
      userGrade: 0,
      sex: 0,
    }
  
  }),
  actions:{
    async setToken({username,password}:any,success:Function,fail:Function ){
      const res = await login({
        username:username.value,
        password:password.value
      })
      if(res.data.code==200){
        console.log("xxa",res.data)
        this.user.token=res.data.data.token;
        this.user.username =username;
        this.user.userId = res.data.data.userId;
        this.user.phoneNumber = res.data.data.phoneNumber;  
        this.user.addressArray = res.data.data.addressArray;
        this.user.balance = res.data.data.balance;
        this.user.nickname = res.data.data.nickname;
        this.user.avatarUrl = res.data.data.avatar;
        this.user.userGrade = res.data.data.userGrade;
        this.user.sex = res.data.data.sex;
        console.log(this.user.avatarUrl);
        localStorage.setItem("user",JSON.stringify(this.user));
          // console.log("xxx",this.user);
        success()
      }else{
        fail(res.data)
      }
    },
    logout() {
      this.user.token = "";
      this.user.username = "";
      this.user.userId = "";
      this.user.phoneNumber = "";
      this.user.addressArray = [];
      this.user.balance = 0;
      this.user.nickname = "";
      this.user.avatarUrl = "";
      this.user.userGrade = 0;
      this.user.sex = 0;
      localStorage.removeItem("user");
    }
  },
  persist:{
    enabled:true,
    strategies:[{
      storage:localStorage,
      key:"user"
    }]
  }
})